const UserService = require("../../services/admin/UserService")
const JWT = require("../../util/JWT")

const UserController = {
  login: async (req, res) => {
    let result = await UserService.login(req.body)
    console.log(result)
    if (result.length === 0) {
      res.send({
        code: '-1',
        error: '用户名密码不匹配'
      })
    } else {
      //生成token
      const token = JWT.generate({
        _id: result[0]._id,
        username: result[0].username
      }, "1d")
      res.header("Authorization", token)
      res.send({
        ActionType: "ok",
        data: {
          username: result[0].username,
          gendar: result[0].gender ? result[0].gender : 0,
          introduction: result[0].introduction,
          avatar: result[0].avatar,
          role: result[0].role,
          userid: result[0]._id
        }
      })
    }
  },
  upload: async (req, res) => {
    const { username, gender, introduction } = req.body
    const token = req.headers["authorization"].split(" ")[1]
    const avatar = req.file ? `/avataruploads/${req.file.filename}` : ''
    let payload = JWT.verify(token)
    await UserService.upload({
      _id: payload._id, username,
      gender: Number(gender), introduction, avatar
    })
    if (avatar) {
      res.send({
        ActionType: 'ok',
        data: {
          gender: Number(gender),
          introduction,
          avatar,
          username
        }
      })
    } else {
      res.send({
        ActionType: 'ok',
        data: {
          gender: Number(gender),
          introduction,
          username
        }
      })
    }

  },
  add: async (req, res) => {
    const { username, gender, introduction, role, password } = req.body
    const avatar = req.file ? `/avataruploads/${req.file.filename}` : ''
    await UserService.add({
      username, gender: Number(gender),
      introduction, role: Number(role), password, avatar
    })
    res.send({
      ActionType: 'ok'
    })
  },
  getList: async (req, res) => {
    const result = await UserService.getList(req.params)
    res.send({
      ActionType: 'ok',
      data: result
    })
  },
  delList: async (req, res) => {
    const result = await UserService.delList({ _id: req.params.id })
    res.send({
      ActionType: 'ok'
    })
  },
  putList: async (req, res) => {
    const result = await UserService.putList(req.body)
    res.send({
      ActionTypep: 'ok'
    })
  }
}
module.exports = UserController